
type PriorityItem<T> = {
    priority: number,
    value: T,
    next: PriorityItem<T> | null
}


export class PriorityLinkList<T> {
    private head: PriorityItem<T> | null = null
    
    put(value: T, priority: number) {
        if (this.head === null) {
            this.head = {
                priority: priority,
                value: value,
                next: null
            }
            return
        }

        let node = this.head

        if (node.priority > priority) {
            this.head = {
                priority: priority,
                value: value,
                next: this.head
            }
            return
        }
        
        while (node) {
            if (node.next === null) {
                node.next = {
                    priority: priority,
                    value: value,
                    next: null
                }
                return
            }
            
            if (node.next.priority > priority) {
                node.next = {
                    priority: priority,
                    value: value,
                    next: node.next
                }
                return
            }

            node = node.next
        }
    }

    [Symbol.iterator](): Iterator<T> {
        let iterHead = this.head

        return {
            next(): IteratorResult<T> {
                if (iterHead !== null) {
                    const val = iterHead.value
                    iterHead = iterHead.next
                    return { value: val, done: false }
                }
                return { value: undefined, done: true }
            }
        }
    }
}

